package com.tx.admin.security.listener;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.tx.admin.modules.rbac.entity.TokenEntity;
import com.tx.admin.modules.rbac.service.TokenService;

@Component
class TokenListener implements SessionListener{


	@Autowired
	private TokenService sessionService;
	
	@Override
	public void onStart(Session session) {
		// TODO Auto-generated method stub

		System.out.println("创建");
		TokenEntity sessionVo = new TokenEntity();
		sessionVo.setId(session.getId().toString());
		sessionVo.setSessionId(session.getId().toString());
		sessionVo.setHost(session.getHost());
		this.sessionService.save(sessionVo);
		session.setAttribute("subject", sessionVo);
	}

	@Override
	public void onStop(Session session) {
		// TODO Auto-generated method stub
		System.out.println("停止");
		this.dropSession(session);

	}
	
	private void dropSession(Session session) {
		TokenEntity sessionVo = (TokenEntity) session.getAttribute("subject");
		if(sessionVo != null) {
			this.sessionService.delete(sessionVo);
		}
	}

	@Override
	public void onExpiration(Session session) {
		// TODO Auto-generated method stub
		this.dropSession(session);
		System.out.println("过期");
	}

}
